package cn.com.cetccst.skf;

import android.util.Log;

import com.westone.skf.ECCCIPHERBLOB;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Utils {
    private static final String TAG = "SKFUtils";

    public static byte[] hexToByte(String hex) {
        int m = 0, n = 0;
        int byteLen = hex.length() / 2; // 每两个字符描述一个字节
        byte[] ret = new byte[byteLen];
        for (int i = 0; i < byteLen; i++) {
            m = i * 2 + 1;
            n = m + 1;
            int intVal = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n));
            ret[i] = Byte.valueOf((byte) intVal);
        }
        return ret;
    }

    public static int bytesToInt(byte[] src) {
        int offset = 0;
        int value;
        value = (int) ((src[offset] & 0xFF)
                | ((src[offset + 1] & 0xFF) << 8)
                | ((src[offset + 2] & 0xFF) << 16)
                | ((src[offset + 3] & 0xFF) << 24));
        return value;
    }

    public static String byteToHex(byte[] bytes) {
        String strHex = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < bytes.length; n++) {
            strHex = Integer.toHexString(bytes[n] & 0xFF);
            sb.append((strHex.length() == 1) ? "0" + strHex : strHex); // 每个字节由两个字符表示，位数不够，高位补0
        }
        return sb.toString().trim();
    }

    public static ECCCIPHERBLOB byteToECCCIPHERBLOB(byte[] bytes) {
        ECCCIPHERBLOB blob = new ECCCIPHERBLOB();
        byte[] x = new byte[64];
        System.arraycopy(bytes, 0, x, 0, x.length);
        blob.setXCoordinate(x);

        byte[] y = new byte[64];
        System.arraycopy(bytes, 64, y, 0, y.length);
        blob.setYCoordinate(y);

        byte[] hash = new byte[32];
        System.arraycopy(bytes, 128, hash, 0, hash.length);
        blob.setHASH(hash);

        int cipherLen = bytes.length - 164;
        byte[] cipher = new byte[cipherLen];
        System.arraycopy(bytes, 164, cipher, 0, cipher.length);
        blob.setCipher(cipher);
        Log.i(TAG, "byteToECCCIPHERBLOB bytes.length: " + bytes.length + " cipherLen: " + cipherLen);

        return blob;
    }

    public static byte[] wrapperEncryptPublicKey(byte[] bytes) {
        try {
            int INVALID_HEADER = 4;
            byte[] wrapperBytes = new byte[bytes.length - INVALID_HEADER];
            System.arraycopy(bytes, INVALID_HEADER, wrapperBytes, 0, wrapperBytes.length);
            return wrapperBytes;
        } catch (Exception e) {
            Log.e(TAG, "wrapperEncrypt error ", e);
        }
        return bytes;
    }
}
